let express = require("express");
let router = express.Router();
var moment = require("moment");
let log = require("cf-nodejs-logging-support");
log.setLoggingLevel("info");

const { ohana } = require("ohana-node-orm");
const tableName = "SAP_JIANGDU_BTP_SERVICE_REQUEST";
const ohana_instance = new ohana(tableName);

const { checkAuth } = require("../utils/utils");
let constants = require("../utils/constants");

const userConfigTableName = "SAP_JIANGDU_USER_CONFIG_SERVICE";

router.get("/", function (req, res, next) {
  // #swagger.tags = ['BTP Service']
  // #swagger.summary = '获取列表'
  // #swagger.description = '需要JWT Token'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  const user = checkAuth(req.user, constants.BASICAUTH);
  if (!user.authCheck) {
    res.sendStatus(403);
  }

  let { USER_ID } = req.query;
  if (user.admin != true && USER_ID == null) {
    res.status(400).send("不准你要所有数据");
  }

  let payload = {};
  if (USER_ID) {
    payload.USER_ID = USER_ID;
  }

  getData(payload)
    .then((result) => {
      res.send(result);
    })
    .catch((err) => {
      log.error(err);
    });
});

router.post("/", function (req, res, next) {
  // #swagger.tags = ['BTP Service']
  // #swagger.summary = '插入列表'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*  #swagger.requestBody = {
              required: true,
              content: {
                  "application/json": {
                      schema: {
                          $ref: "#/definitions/btp_add"
                      }  
                  },
              }
      } */
  const user = checkAuth(req.user, constants.BASICAUTH);
  if (!user.authCheck) {
    res.sendStatus(403);
  }
  let { data } = req.body;
  data.USER_ID = user.user_id;
  data.CREATED_AT = moment().format("YYYY-MM-DD HH:mm:ss");
  data.STATUS = constants.STATUSINITIAL;
  insertData(data)
    .then((result) => {
      if (result == 1) {
        res.sendStatus(200);
      } else {
        res.sendStatus(500);
      }
    })
    .catch((err) => {
      log.error(err);
    });
});

router.put("/", function (req, res, next) {
  // #swagger.tags = ['BTP Service']
  // #swagger.summary = '更新列表'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*  #swagger.requestBody = {
              required: true,
              content: {
                  "application/json": {
                      schema: {
                          $ref: "#/definitions/btp_update"
                      }  
                  },
              }
      } */
  const { data } = req.body;
  const user = checkAuth(req.user, constants.BASICAUTH);
  if (!user.authCheck) {
    res.sendStatus(403);
  }
  if(data.BTPTEXT)
  {
    delete data.BTPTEXT;
  }
  updateData(data)
    .then((result) => {
      if (result >= 2) {
        res.sendStatus(200);
      } else {
        res.sendStatus(500);
      }
    })
    .catch((err) => {
      log.error(err);
    });
});

router.delete("/", function (req, res, next) {
  // #swagger.tags = ['BTP Service']
  // #swagger.summary = '删除列表'
  /* #swagger.security = [{
               "JiangduJWT": []
  }] */
  /*  #swagger.requestBody = {
              required: true,
              content: {
                  "application/json": {
                      schema: {
                          $ref: "#/definitions/btp_delete"
                      }  
                  },
              }
      } */
 
      const { data } = req.body;
      const user = checkAuth(req.user, constants.BASICAUTH);
      if (!user.authCheck) {
        res.sendStatus(403);
      }
      if(!data.USER_ID||!data.SERVICE)
      {
        res.sendStatus(400)
        return;
      }
      deleteData(data)
    .then((result) => {
      if (result == 1) {
        res.sendStatus(200);
      } else {
        res.sendStatus(500);
      }
    })
    .catch((err) => {
      log.error(err);
    });
});

async function getData(condition) {
  let result = [];
  result = await ohana_instance.find(condition);
  return result;
}

async function insertData(data) {
  let result = await ohana_instance.insert(data);
  return result;
}

async function updateData(data) {
  Object.keys(data).forEach((item) => {
    if (!data[item] || data[item] == "") delete data[item];
  });
  let result = await ohana_instance.update(
    {
      USER_ID: data.USER_ID,
      SERVICE: data.SERVICE,
    },
    data
  );
  var ohaneNew = new ohana(userConfigTableName);
  let userConfigResult = await ohaneNew.update(
    {
      USER_ID: data.USER_ID,
      AUTH: data.SERVICE,
    },
    {
      URL: data.URL,
    }
  );

  return result + userConfigResult;
}

async function deleteData(data) {
  let result = ohana_instance.raw(
    'delete from "' + tableName + "\" where USER_ID = '" + data.USER_ID + "' and SERVICE ='"+data.SERVICE+"'"
  );
  return result;
}

module.exports = router;
